package qwq.zyu.BingoSidebar;

import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scoreboard.*;

import java.util.*;

public class qwqBingoSidebarCommand implements CommandExecutor {
    private final Plugin plugin;
    private final Map<String, BukkitRunnable> taskMap = new HashMap<>();

    private final Scoreboard scoreboard;
    public qwqBingoSidebarCommand(Plugin plugin) {
        this.plugin = plugin;
        ScoreboardManager scoreboardManager = Bukkit.getScoreboardManager();
        assert scoreboardManager != null;
        this.scoreboard = scoreboardManager.getNewScoreboard();
    }

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        if ( args.length != 1 ){
            sender.sendMessage("用法: /qwq_bingo_sidebar <enable? true/false>");
            return false;
        }

        boolean arg1 = Boolean.parseBoolean(args[0]);

        String ONLY_KEY = "foo";
        if ( arg1 == true ){
            if (taskMap.containsKey(ONLY_KEY)){
                sender.sendMessage("sidebar的更新任务已经在运行。");
                return false;
            } else {
                BukkitRunnable task = new BukkitRunnable() {
                    @Override
                    public void run() {
                        updateSidebar();
                    }
                };

                task.runTaskTimer(plugin, 0, 20*10);
                taskMap.put(ONLY_KEY,  task);

                sender.sendMessage("已经开启sidebar的更新任务");
            }
        } else {
            if ( taskMap.containsKey(ONLY_KEY)){
                taskMap.get(ONLY_KEY).cancel();
                taskMap.remove(ONLY_KEY);
                sender.sendMessage("已经停止sidebar更新");
            } else {
                sender.sendMessage("没有sidebar更新任务！停什喵！");
            }
        }
        return true;
    }

    private void updateSidebar(){
        Objective sidebarObjective = scoreboard.getObjective("teamDisplay");

        if ( sidebarObjective==null ){
            sidebarObjective = scoreboard.registerNewObjective("teamDisplay", "dummy", "---队伍---");
        }
        sidebarObjective.setDisplaySlot(DisplaySlot.SIDEBAR);

        HashMap<String, Integer> teamPlayersMap = new HashMap<>();
        HashMap<String, Integer> teamScoresMap = new HashMap<>();
        String[] ChineseColorName = {"无","红","黄", "绿", "蓝"};
        HashMap<String, List<String>> teamMemberMap = new HashMap<>();  // 用于存储队伍成员

        for ( Player player: Bukkit.getOnlinePlayers() ){
            int entry_value_int = getTeamValue(player);
            String teamName = ChineseColorName[entry_value_int];

            // 添加队伍成员到队伍列表
            teamMemberMap.computeIfAbsent(teamName, k -> new ArrayList<>()).add(player.getName());

            // 更新队伍的分数
            teamScoresMap.put(teamName, teamScoresMap.getOrDefault(teamName, 0) + 1);  // 这里假设分数为队伍成员数量
        }

        // 先按队伍顺序处理
        List<String> teamOrder = Arrays.asList("红", "黄", "绿", "蓝");
        for (String teamName : teamOrder) {
            // 添加队伍名称行（加粗）
            String teamLine = teamName + "队（加粗）";
            sidebarObjective.getScore(teamLine).setScore(teamScoresMap.getOrDefault(teamName, 0));

            // 获取并排序队伍内玩家的名字
            List<String> sortedPlayers = teamMemberMap.getOrDefault(teamName, new ArrayList<>());
            Collections.sort(sortedPlayers);

            // 添加玩家名字行
            for (String playerName : sortedPlayers) {
                String displayName = teamName + "【" + playerName + "】";
                int score = getTeamValue(Bukkit.getPlayer(playerName));  // 获取对应的队伍分数
                sidebarObjective.getScore(displayName).setScore(score);
            }
        }

        Bukkit.getOnlinePlayers().forEach(p -> p.setScoreboard(scoreboard));
    }

    private String getTeamName(Player player) {
        if (player.getScoreboard().getEntryTeam(player.getName()) == null) {
            return "none";
        }
        return player.getScoreboard().getEntryTeam(player.getName()).getName();
    }

    // 根据队伍设置分数
    private int getTeamValue(Player player) {
        String teamName = getTeamName(player);
        return switch (teamName) {
            case "red" -> 1;  // 红队
            case "yellow" -> 2;  // 黄队
            case "green" -> 3;  // 绿队
            case "blue" -> 4;  // 蓝队
            default -> 0;  // 无队伍
        };
    }
}
